package com.gitee.empty_null.authorization.configurer;

import com.gitee.empty_null.authorization.provider.OAuth2UsernamePasswordAuthenticationProvider;
import com.gitee.empty_null.authorization.utils.OAuth2ConfigurerUtils;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;

/**
 * @author xuhainan
 * @date 2024/1/16 09:27
 * @region hefei
 */
public class OAuth2AuthenticationProviderConfigurer extends AbstractHttpConfigurer<OAuth2AuthenticationProviderConfigurer, HttpSecurity> {



    private final PasswordEncoder passwordEncoder;
    private final UserDetailsService userDetailsService;

    public OAuth2AuthenticationProviderConfigurer(PasswordEncoder passwordEncoder, UserDetailsService userDetailsService) {
        this.passwordEncoder = passwordEncoder;
        this.userDetailsService = userDetailsService;
    }


    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        OAuth2AuthorizationService authorizationService = OAuth2ConfigurerUtils.getAuthorizationService(httpSecurity);
        OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator = OAuth2ConfigurerUtils.getTokenGenerator(httpSecurity);

        OAuth2UsernamePasswordAuthenticationProvider usernamePasswordAuthenticationProvider =
                new OAuth2UsernamePasswordAuthenticationProvider(authorizationService, tokenGenerator, userDetailsService);
        usernamePasswordAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        SessionRegistry sessionRegistry = httpSecurity.getSharedObject(SessionRegistry.class);
        if (sessionRegistry != null) {
            usernamePasswordAuthenticationProvider.setSessionRegistry(sessionRegistry);
        }
        httpSecurity.authenticationProvider(usernamePasswordAuthenticationProvider);


    }
}
